from fastapi import APIRouter, Query,UploadFile,BackgroundTasks
from tortoise.expressions import Q

from app.controllers.appointment.space import appointment_space_controller
from app.controllers.customer.users import users_controller
from app.controllers.orders.goods import orders_goods_controller
from app.controllers.orders.wechat import wechat_controller
from app.models import OrdersList, OrdersGoods
from app.settings import settings
from app.controllers.orders.list import orders_list_controller
from app.schemas.base import Success, SuccessExtra,Fail
from app.schemas.orders import *
from app.models.customer import CustomerUser
from app.utils.excel import create_excel,date_format
from fastapi.responses import JSONResponse

orders_list_router = APIRouter()
model_name = "订单"


@orders_list_router.get("/list", summary=f"查看{model_name}列表")
async def do_orders_list(
        page: int = Query(1, description="页码"),
        page_size: int = Query(10, description="每页数量"),
        user_name: str = Query(None, description=f"下单人名称"),
        status: int = Query(0, description="订单状态"),
        start_time: str = Query("", description="开始时间"),
        end_time: str = Query("", description="结束时间"),
        is_express: int = Query(-1, description="发货状态"),
        type: int = Query(-1, description="订单类型"),
):
    search_user_ids = []
    if user_name:
        search_users = await CustomerUser.filter(name__contains=user_name).values("id")
        search_user_ids = {orders['id'] for orders in search_users}  # 获取所有的 user_id
    q = Q(type__in=[2,3,4])
    if status:
        q &= Q(status=status)
    if is_express > -1:
        q &= Q(is_express=is_express)
    if type>-1:
        q &= Q(type=type)
    if user_name:
        q &= Q(user_id__in=search_user_ids)
    if start_time and end_time:
        q &= Q(pay_time__range=[start_time, end_time])
    elif start_time:
        q &= Q(pay_time__gte=start_time)
    elif end_time:
        q &= Q(pay_time__lte=end_time)
    total, data = await orders_list_controller.do_list(page=page, page_size=page_size, search=q)
    user_ids = {orders['user_id'] for orders in data}  # 获取所有的 user_id
    users = await CustomerUser.filter(id__in=user_ids)
    users_dict = {user.id: user for user in users}
    space_objs = await appointment_space_controller.level_list()
    for orders in data:
        user = users_dict.get(orders['user_id'])
        if user:
            orders['user_name'] = user.name
            orders['user_phone'] = user.phone  # 设置一个默认值
        else:
            orders['user_name'] = "用户已被删除"  # 设置一个默认值
            orders['user_phone'] = ""  # 设置一个默认值
        orders['status_name'] = settings.ORDERS_STATUS[orders['status']]
        orders['express_name'] = settings.EXPRESS_STATUS[orders['is_express']]
        if orders['address_id']>0:
            orders['address_name'] = space_objs[orders['address_id']]
    return SuccessExtra(data=data, total=total, page=page, page_size=page_size)



@orders_list_router.get("/dd_list", summary=f"查看{model_name}列表")
async def do_orders_list(
        page: int = Query(1, description="页码"),
        page_size: int = Query(10, description="每页数量"),
        user_name: str = Query(None, description=f"下单人名称"),
        status: int = Query(0, description="订单状态"),
        start_time: str = Query("", description="开始时间"),
        end_time: str = Query("", description="结束时间"),
        is_express: int = Query(-1, description="发货状态"),
):
    search_user_ids = []
    if user_name:
        search_users = await CustomerUser.filter(name__contains=user_name).values("id")
        search_user_ids = {orders['id'] for orders in search_users}  # 获取所有的 user_id
    q = Q(type=1)
    # q &= Q(status__gte=1)
    if status:
        q &= Q(status=status)
    if is_express>-1:
        q &= Q(is_express=is_express)
    if user_name:
        q &= Q(user_id__in=search_user_ids)
    if start_time and end_time:
        q &= Q(pay_time__range=[start_time, end_time])
    elif start_time:
        q &= Q(pay_time__gte=start_time)
    elif end_time:
        q &= Q(pay_time__lte=end_time)
    total, data = await orders_list_controller.do_list(page=page, page_size=page_size, search=q)
    user_ids = {orders['user_id'] for orders in data}  # 获取所有的 user_id
    users = await CustomerUser.filter(id__in=user_ids)
    users_dict = {user.id: user for user in users}
    space_objs = await appointment_space_controller.level_list()
    for orders in data:
        user = users_dict.get(orders['user_id'])
        if user:
            orders['user_name'] = user.name
            orders['user_phone'] = user.phone  # 设置一个默认值
        else:
            orders['user_name'] = "用户已被删除"  # 设置一个默认值
            orders['user_phone'] = ""  # 设置一个默认值
        orders['status_name'] = settings.ORDERS_STATUS[orders['status']]
        orders['express_name'] = settings.EXPRESS_STATUS_DD[orders['is_express']]
        if orders['address_id']>0:
            orders['address_name'] = space_objs[orders['address_id']]
    return SuccessExtra(data=data, total=total, page=page, page_size=page_size)



@orders_list_router.get("/get", summary=f"查看{model_name}")
async def do_orders_get(
        data_id: int = Query(..., description="ID"),
):
    data = await orders_list_controller.do_get(data_id=data_id)
    user = await CustomerUser.filter(id=data['user_id']).first().values("name","card_no","role_id","phone")
    level_objs = await users_controller.level_list()
    data['user_name'] = user["name"]
    data['user_card_no'] = user["card_no"]
    data['user_phone'] = user["phone"]
    data['user_type'] = level_objs[user["role_id"]]
    data['status_name'] = settings.ORDERS_STATUS[data['status']]
    data['express_name'] = settings.EXPRESS_STATUS[data['is_express']]
    return Success(data=data)

@orders_list_router.post("/update", summary=f"更新{model_name}")
async def do_orders_update(
        data_in: OrdersListUpdate,
):
    await orders_list_controller.do_update(obj_in=data_in)
    return Success(msg="更新成功")

@orders_list_router.post("/update_dd", summary=f"更新点单{model_name}制作状态")
async def do_orders_update(
        data_in: OrdersListUpdate,
):
    await OrdersList.filter(id=data_in.id).update(is_express=data_in.is_express)
    message_in = SendMessage(
        open_id="",
        user_id=data_in.user_id,
        order_id=data_in.id
    )
    await wechat_controller.send_order_message(data_in=message_in)
    return Success(msg="更新成功")

@orders_list_router.post("/refund", summary=f"作废/退款{model_name}")
async def do_orders_refund(
        data_id: OrdersListRefund,
):
    ret = await orders_list_controller.order_refund(order_id=data_id.order_id,order_status=data_id.order_status)
    if ret["refund_status"] == 1:
        return Success(msg="作废/退款成功", data=ret)
    else:
        return Fail(msg=ret["msg"])

@orders_list_router.get("/success", summary=f"线下收款{model_name}")
async def do_orders_refund(
        data_id: int = Query(..., description="ID"),
):
    ret = await orders_list_controller.order_success(order_id=data_id,out_trade_no=0)
    if ret["pay_status"] == 1:
        return Success(msg="收款成功")
    else:
        return Fail(msg=ret["msg"])

@orders_list_router.delete("/delete", summary=f"删除{model_name}")
async def do_orders_delete(
        data_id: int = Query(..., description="ID"),
):
    await orders_list_controller.do_delete(data_id=data_id)
    return Success(msg="删除成功")

@orders_list_router.get("/type", summary="获取订单类型")
async def doctor_type():
    level_objs = settings.ORDERS_STATUS
    data = []
    key = 0
    for level in level_objs:
        if level:
            data.append({"label":level,"value":key})
        key += 1
    return Success(data=data)

@orders_list_router.get("/excel", summary="导出数据")
async def list_excel(
        back_tasks: BackgroundTasks,
        user_name: str = Query(None, description=f"下单人名称"),
        status: int = Query(0, description="订单状态"),
        start_time: str = Query("", description="开始时间"),
        end_time: str = Query("", description="结束时间"),
):
    search_user_ids = []
    if user_name:
        search_users = await CustomerUser.filter(name__contains=user_name).values("id")
        search_user_ids = {orders['id'] for orders in search_users}  # 获取所有的 user_id
    q = Q()
    if status:
        q &= Q(status=status)
    if user_name:
        q &= Q(user_id__in=search_user_ids)
    if start_time and end_time:
        q &= Q(pay_time__range=[start_time, end_time])
    elif start_time:
        q &= Q(pay_time__gte=start_time)
    elif end_time:
        q &= Q(pay_time__lte=end_time)
    name = f"订单数据{start_time}~{end_time}"
    data = await OrdersList.filter(q).all().values(
        单号='id',
        流水号='water_no',
        订单类型='type',
        总金额='price',
        优惠金额='sale_price',
        运费='express_price',
        储值金='deposit_price',
        优惠券='coupons_price',
        实际支付='amount_price',
        订单状态="status",
        下单人="user_id",
        下单时间="created_at",
        付款时间="pay_time",
        物流状态="is_express",
        收件人="receive_name",
        收件电话="receive_phone",
        收件地址="receive_address",

    )

    user_ids = {orders['下单人'] for orders in data}  # 获取所有的 user_id
    users = await CustomerUser.filter(id__in=user_ids)
    users_dict = {user.id: user.name for user in users}

    for item in data:
        item["下单时间"] = date_format(item["下单时间"])
        if item["付款时间"]:
            item["付款时间"] = date_format(item["付款时间"])
        item['物流状态'] = settings.EXPRESS_STATUS[item['物流状态']]
        item['订单类型'] = settings.GOODS_TYPE[item['订单类型']]
        item['订单状态'] = settings.ORDERS_STATUS[item['订单状态']]
        item['下单人']  = users_dict.get(item['下单人'], "已删除用户")

    back_tasks.add_task(create_excel, name=name,data=data)
    return JSONResponse(content={"code": 200, "message": "开始生成excel,请去下载中心查看"}, status_code=200)

@orders_list_router.get("/after_list", summary=f"售后处理列表")
async def do_orders_after_list(
        page: int = Query(1, description="页码"),
        page_size: int = Query(10, description="每页数量"),
        user_name: str = Query(None, description=f"下单人名称"),
        start_time: str = Query("", description="开始时间"),
        end_time: str = Query("", description="结束时间"),
):
    search_user_ids = []
    if user_name:
        search_users = await CustomerUser.filter(name__contains=user_name).values("id")
        search_user_ids = {orders['id'] for orders in search_users}  # 获取所有的 user_id
    q = Q(status__in = [3,4])
    if user_name:
        q &= Q(user_id__in=search_user_ids)
    if start_time and end_time:
        q &= Q(pay_time__range=[start_time, end_time])
    elif start_time:
        q &= Q(pay_time__gte=start_time)
    elif end_time:
        q &= Q(pay_time__lte=end_time)
    total, data = await orders_list_controller.do_list(page=page, page_size=page_size, search=q)
    user_ids = {orders['user_id'] for orders in data}  # 获取所有的 user_id
    users = await CustomerUser.filter(id__in=user_ids).distinct().all()
    users_dict = {user.id: user for user in users}
    for orders in data:
        user = users_dict.get(orders['user_id'])
        if user:
            orders['user_name'] = user.name
            orders['user_phone'] = user.phone  # 设置一个默认值
        else:
            orders['user_name'] = "用户已被删除"  # 设置一个默认值
            orders['user_phone'] = ""  # 设置一个默认值
        orders['status_name'] = settings.ORDERS_STATUS[orders['status']]
        orders['express_name'] = settings.EXPRESS_STATUS[orders['is_express']]

    return SuccessExtra(data=data, total=total, page=page, page_size=page_size)


@orders_list_router.get("/daiban_list", summary=f"查看待办列表")
async def do_daiban_list(
        page: int = Query(1, description="页码"),
        page_size: int = Query(20, description="每页数量"),
):
    q = Q(status=1)
    total, data = await orders_list_controller.do_list(page=page, page_size=page_size, search=q)
    return SuccessExtra(data=data, total=total, page=page, page_size=page_size)